from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from .models import Areas
from .serializers import AreasProvincesSerializer, AreasDetailSerializer


# 1. 继承APIView完成

# class AreasProvincesView(APIView):
#     """获取所有的省"""
#     def get(self, request):
#         # 获取所有省数据
#         provinces = Areas.objects.filter(parent=None)
#
#         serializers = AreasProvincesSerializer(instance=provinces, many=True)
#
#         return Response(serializers.data)
#
#
# class AreasDetailsView(APIView):
#     """获取省，市的单一数据"""
#     def get(self, request, area_id):
#         try:
#             area = Areas.objects.get(id=area_id)
#         except Areas.DoesNotExist:
#             return Response({'message': '没有此行政区域'}, status=status.HTTP_400_BAD_REQUEST)
#
#         serializers = AreasDetailSerializer(instance=area)
#
#         return Response(serializers.data)


# 继承ListAPIView, RetrieveAPIView完成

# class AreasProvincesView(ListAPIView):
#     """获取所有的省"""
#     # 指定查询集
#     queryset = Areas.objects.filter(parent=None)
#     # 指定序列化器
#     serializer_class = AreasProvincesSerializer
#
#
# class AreasDetailsView(RetrieveAPIView):
#     """获取省，市的单一数据"""
#     queryset = Areas.objects.all()
#
#     # lookup_field = 'id'  # 查询单一数据库对象时使用的条件字段，默认为 pk
#     lookup_url_kwarg = 'area_id'  # 查询单一数据时URL中的参数关键字名称 默认与lookup_field相同
#
#     serializer_class = AreasDetailSerializer

# 使用视图集完成，两个view合并为一个

class AreaViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    """获取所有省市区数据"""
    # CacheResponseMixin缓存查询的返回的所有数据到redis中
    # 指定查询集
    pagination_class = None  # 禁用分页

    def get_queryset(self):
        if self.action == 'list':
            return Areas.objects.filter(parent=None)
        else:
            return Areas.objects.all()

    # 指定序列化器
    def get_serializer_class(self):
        if self.action == 'list':
            return AreasProvincesSerializer
        else:
            return AreasDetailSerializer
